<template>
  <div class="components-container">
    <el-upload
      action="#"
      :http-request="fnUploadRequestFiles"
      list-type="picture-card"
      :file-list="fileList"
      :limit="limit"
      :on-success="uploadSuccessFiles"
      :before-upload="beforeFileUpload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-exceed="handleExceed"
      multiple
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import oss from '@/utils/aliyunOssCommon'
export default {
  name: 'MultiFileUpload',
  props: {
    tip: {
      type: String,
      default: '图片类型必须是gif，jpg，jpeg，png，GIF，JPG，PNG中的一种'
    },
    size: {
      type: Number,
      default: 2
    },
    limit: {
      type: Number,
      default: 5
    },
    fileList: {
      type: Array,
      default() {
        return []
      }
    },
    path: {
      type: String,
      default: 'content/'
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  methods: {
    beforeFileUpload(file) {
      const isLt50M = file.size / 1024 < 1024 * this.size
      const isImg = this.checkImgType(file.name)
      if (!isLt50M) {
        this.$message.error('文件大小' + this.size + 'MB以下')
        return false
      }
      if (!isImg) {
        this.$message.error(this.tip)
        return false
      }
      return true
    },
    uploadSuccessFiles(response, file, fileList) {
      if (file.response) {
        this.$emit('onSuccess', file.response.url)
      }
    },
    async fnUploadRequestFiles(option) {
      const doIndex = option.file.name.lastIndexOf('.')
      const nameLen = option.file.name.length
      const suffix = option.file.name.substring(doIndex, nameLen)
      oss.ossUploadFile(option, this.path, new Date().getTime() + suffix)
    },
    handleRemove(file, fileList) {
      this.$emit('onRemove', file.url)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    checkImgType(ths) {
      if (ths === '') {
        return false
      } else {
        if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(ths)) {
          return false
        }
      }
      return true
    }
  }
}
</script>
<style scoped>
  .editor-content{
    margin-top: 20px;
  }
</style>
